package co.fitstart.admin.web.controller.trade.order;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;
import co.fitstart.admin.cache.accessor.PersistentAccessor;
import co.fitstart.admin.entity.search.OrderSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.handler.PaymentHandler;
import co.fitstart.admin.service.CouponService;
import co.fitstart.admin.service.OrderService;
import co.fitstart.admin.service.ProductService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.coupon.DiscountType;
import co.fitstart.entity.course.CourseType;
import co.fitstart.entity.course.CourseUnit;
import co.fitstart.entity.finance.Receipt;
import co.fitstart.entity.finance.ReceiptType;
import co.fitstart.entity.order.Order;
import co.fitstart.entity.order.OrderInvestigateRecord;
import co.fitstart.entity.order.OrderStatus;
import co.fitstart.entity.order.OrderType;
import co.fitstart.entity.order.PaymentMethod;
import co.fitstart.entity.order.PaymentStatus;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.product.Product;
import co.fitstart.entity.reference.Contact;
import co.fitstart.entity.site.Site;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("{type}-orders")
@MenuSetting("menu-ecommerce")
public class OrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private SiteService siteService;
    
    @Autowired
    private PaymentHandler paymentHandler;
    
    @Autowired
    private PersistentAccessor persistentAccessor;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Autowired
    private CouponService<Coupon> couponService;
    
    /**
     * List orders by type & status
     * 
     * @param login
     * @param type
     * @param orderStatus
     * @param siteId
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-{type}-order-management")
    public ModelAndView list(@Secure Login login,
                             @PathVariable("type") String type,
                             @RequestParam("status") String orderStatus,
                             @RequestParam(value = "siteId", required = false) Long siteId,
                             HttpServletRequest request,
                             Page page) {
        ModelAndView modelAndView;
        if("give".equals(type)) {
            modelAndView = new ModelAndView("ecommerce/order/individual-order-list");
        } else {
            modelAndView = new ModelAndView("ecommerce/order/" + type + "-order-list");
        }
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("status", orderStatus);
        
        OrderType orderType;
        boolean experience = false;
        boolean give = false;
        if("experience".equals(type)) {
            orderType = OrderType.INDIVIDUAL;
            experience = true;
        } else if("give".equals(type)) {
            orderType = OrderType.INDIVIDUAL;
            give = true;
        } else {
            orderType = OrderType.aliasOf(type);
        }
        
        List<Order> orders = new ArrayList<>();
        
        if (orderType.isOnline() || orderType.isOthers() || orderType.isActivity()) {
            // list Online Orders or Others Orders
            
            orders = orderService.listByPage(orderType, orderStatus, page);
        } else if (!login.hasSite() && siteId == null) {
            // list Individual Orders or Group Orders or Year Orders
            
            if(login.isAreaManager() || login.isAreaServer()) {
                Principal principal = genericDaoSupport.load(Principal.class, login.getId());
                
                List<Site> sites = siteService.listSite(principal);
                
                if(!sites.isEmpty()) {
                    if(orderType.isIndividual()) {
                        orders = orderService.listByPage(sites, experience, give, orderStatus, page);
                    } else {
                        orders = orderService.listByPage(sites, orderType, orderStatus, page);
                    }
                }
            } else {
                if(orderType.isIndividual()) {
                    orders = orderService.listByPage(experience, give, orderStatus, page);
                } else {
                    orders = orderService.listByPage(orderType, orderStatus, page);
              }
            }
        } else if (!login.hasSite() && siteId != null) {
            // list Individual Orders or Group Orders or Year Orders by site (ROLE_ADMIN user)
            
            Site site = siteService.load(siteId);
            if(orderType.isIndividual()) {
                orders = orderService.listByPage(site, experience, give, orderStatus, page);
            } else {
                orders = orderService.listByPage(site, orderType, orderStatus, page);
            }
        } else if (login.hasSite()) {
            // list Individual Orders or Group Orders or Year Orders by site (ROLE_SITE user)
            
            Site site = login.getSite();
            if(orderType.isIndividual()) {
                orders= orderService.listByPage(site, experience, give, orderStatus, page);
            } else {
                orders= orderService.listByPage(site, orderType, orderStatus, page);
            }
        }
        
        modelAndView.addObject("orders",orders);
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * display search view
     * 
     * @param type
     * @param status
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search(@PathVariable("type") String type,
                               @RequestParam("status") String status,
                               @RequestParam(value = "siteId", required = false) Long siteId) {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/order-search");
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("status", status);
        modelAndView.addObject("siteId", siteId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param orderSearch
     * @param type
     * @param orderStatus
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-{type}-order-management")
    public ModelAndView onSearch(@Secure Login login,
                                 OrderSearch orderSearch,
                                 @PathVariable("type") String type,
                                 @RequestParam("status") String orderStatus,
                                 @RequestParam(value = "siteId", required = false) Long siteId,
                                 HttpServletRequest request, 
                                 Page page) {
        ModelAndView modelAndView;
        if("give".equals(type)) {
            modelAndView = new ModelAndView("ecommerce/order/individual-order-list");
        } else {
            modelAndView = new ModelAndView("ecommerce/order/" + type + "-order-list");
        }
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("status", orderStatus);
        
        OrderType orderType;
        if("experience".equals(type)) {
            orderType = OrderType.INDIVIDUAL;
            orderSearch.setExperience(true);
        } else if("give".equals(type)) {
            orderType = OrderType.INDIVIDUAL;
            orderSearch.setGive(true);
        } else {
            orderType = OrderType.aliasOf(type);
        }
        orderSearch.setOrderType(orderType);
        
        if(login.hasSite()) {
            orderSearch.setSite(login.getSite());
        } else if(siteId != null) {
            orderSearch.setSite(siteService.load(siteId));
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = genericDaoSupport.load(Principal.class, login.getId());
            
            orderSearch.setSites(siteService.listSite(principal));
        }
        
        if(orderSearch.getSites() == null || !orderSearch.getSites().isEmpty()) {
            // list order by page & status
            List<Order> orders = orderService.search(orderSearch, page);
            modelAndView.addObject("orders",orders);
            
            // get total
            int total = orderService.totalOrder(orderSearch);
            modelAndView.addObject("total",total);
        } else {
            modelAndView.addObject("total",0);
        }
        
        // add query string
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param type
     * @param status
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET, params="orderSearch")
    public ModelAndView searchOrderNumber(@PathVariable("type") String type,
                                          @RequestParam("status") String status) {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/order-number-search");
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("status", status);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param type
     * @param orderStatus
     * @param orderNumber
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filters")
    @MenuSetting("submenu-{type}-order-management")
    public ModelAndView onSearchOrderNumber(@Secure Login login,
                                            @PathVariable("type") String type,
                                            @RequestParam("status") String orderStatus,
                                            @RequestParam("orderNumber") String orderNumber,
                                            HttpServletRequest request, 
                                            Page page) {
        ModelAndView modelAndView;
        if("give".equals(type)) {
            modelAndView = new ModelAndView("ecommerce/order/individual-order-list");
        } else {
            modelAndView = new ModelAndView("ecommerce/order/" + type + "-order-list");
        }
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("status", orderStatus);
        
        Long orderId = orderService.getOrderId(orderNumber);
        
        // list order by page & status
        List<Order> orders = new ArrayList<Order>();
        if(orderId != null) {
            if("experience".equals(type)) {
                orders = orderService.search(true, false, OrderStatus.aliasOf(orderStatus), orderId, page);
            } else if("give".equals(type)) {
                orders = orderService.search(false, true, OrderStatus.aliasOf(orderStatus), orderId, page);
            } else if(OrderType.aliasOf(type).isIndividual()) {
                orders = orderService.search(false, false, OrderStatus.aliasOf(orderStatus), orderId, page);
            } else {
                orders = orderService.search(OrderType.aliasOf(type), OrderStatus.aliasOf(orderStatus), orderId, page);
            }
            modelAndView.addObject("orders",orders);
        }
        
        // get total
        int total = orders.size();
        modelAndView.addObject("total",total);
        
        // add query string
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
    }
    
    /**
     * Do export order
     * 
     * @param login
     * @param orderSearch
     * @param type
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 OrderSearch orderSearch,
                                 @PathVariable("type") String type,
                                 @RequestParam(value = "siteId", required = false) Long siteId){
        OrderType orderType;
        if("experience".equals(type)) {
            orderType = OrderType.INDIVIDUAL;
            orderSearch.setExperience(true);
        } else if("give".equals(type)) {
            orderType = OrderType.INDIVIDUAL;
            orderSearch.setGive(true);
        } else {
            orderType = OrderType.aliasOf(type);
        }
        orderSearch.setOrderType(orderType);
        
        if(login.hasSite()) {
            orderSearch.setSite(login.getSite());
        } else if(siteId != null) {
            orderSearch.setSite(siteService.load(siteId));
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = genericDaoSupport.load(Principal.class, login.getId());
            
            orderSearch.setSites(siteService.listSite(principal));
        }
        
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView(type + "Order.xls"));
        
        List<Order> orders = orderService.exportOrder(orderSearch);
        
        int total = orderService.totalOrder(orderSearch);
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        modelAndView.addObject("total", total);
        modelAndView.addObject("orders", orders);
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }
    
    /**
     * view order detail page
     * 
     * @param orderId
     * @param orderType 
     * @return
     */
    @RequestMapping(value= "/{orderId}", method = RequestMethod.GET)
    @MenuSetting("submenu-{type}-order-management")
    public ModelAndView view(@PathVariable("orderId") Long orderId, @PathVariable("type") String orderType,
                             @RequestParam(name = "status", required = false) String orderStatus){
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/view/order-view");
        
        Order order = orderService.loadOrder(orderId);
        OrderInvestigateRecord orderInvestigateRecord = persistentAccessor.orderInvestigationRecord(order);
        
        //定金及（部分支付过的）付款记录
        List<Receipt> receipts = orderService.listReceipt(order);
        
        //是否操作过部分支付
        boolean flag = false;
        int deposit = 0;
        if(receipts != null) {
            for(Receipt receipt : receipts) {
                if(receipt.getType() == ReceiptType.BALANCE) {
                    flag = true;
                } else if(receipt.getType() == ReceiptType.DEPOSIT) {
                    deposit += receipt.getDomesticPrice();
                }
            }
        }
        
        //（未部分支付过的）付款记录
        if(!flag && order.getPaymentStatus() != PaymentStatus.UNPAID && order.getPaymentStatus() != PaymentStatus.CANCELED) {
            Map<String, Object> otherReceipt = new HashMap<>();
            if(order.getAttrs() != null && order.getAttrs().get("paid_price") != null && order.getAttrs().get("paid_price").getValue() != null) {
                otherReceipt.put("domesticPrice", Integer.parseInt(order.getAttrs().get("paid_price").getValue()));
            } else {
                otherReceipt.put("domesticPrice", order.getPrice() - deposit);
            }
            
            modelAndView.addObject("otherReceipt",otherReceipt);
        }
        
        modelAndView.addObject("investigate", orderInvestigateRecord);
        modelAndView.addObject("order",order);
        modelAndView.addObject("receipts",receipts);
        modelAndView.addObject("status", orderStatus);
        modelAndView.addObject("type", orderType);
        return modelAndView;
        
    }

    /**
     * Order profile view page
     * 
     * @param orderId
     * @param orderType 
     * @return
     */
    @RequestMapping(value = "/{orderId}/product", method = RequestMethod.GET, params="view")
    @MenuSetting("submenu-{type}-order-management")
    public ModelAndView productView(@PathVariable("orderId") Long orderId, @PathVariable("type") String orderType){
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/view/order-product-view");
        
        Order order = orderService.loadOrder(orderId);
        modelAndView.addObject("order",order);
        
        modelAndView.addObject("type", orderType);
        return modelAndView;
    }
    
    /**
     * Investigation view page
     * 
     * @param orderId
     * @param orderType 
     * @return
     */
    @RequestMapping(value = "/{orderId}/investigate", method = RequestMethod.GET)
    @MenuSetting("submenu-{type}-order-management")
    public ModelAndView investigation(@PathVariable("orderId") Long orderId, @PathVariable("type") String orderType,
                                      @RequestParam("investigateType") String investigateType){
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/view/order-" + investigateType + "-investigate-view");
        
        Order order = orderService.loadOrder(orderId);
        OrderInvestigateRecord orderInvestigateRecord = persistentAccessor.orderInvestigationRecord(order);
        
        modelAndView.addObject("investigate", orderInvestigateRecord);
        modelAndView.addObject("investigateType", investigateType);
        modelAndView.addObject("order",order);
        
        modelAndView.addObject("type", orderType);
        return modelAndView;
    }
    
    /**
     * display create page
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create() {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/operations/order-create");
        
        return modelAndView;
        
    }
    
    /**
     * do create
     * 
     * @param contact 
     * @param paymentMethod
     * @param productId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(Contact contact,
                                         PaymentMethod paymentMethod,
                                         @RequestParam("productId") Long productId) {
        
        Result result = new Result();
        
        try {
            
            Product product = productService.load(Product.class, productId);
            
            // Step1 create order by product & 
            Order order = orderService.createOnline(product, contact, paymentMethod);
            
            String orderNo = order.getCode();
            Long customerId = order.getUser().getId();
            int amount = order.getPrice();
            String requestNo = "ADMIN_CREATED_ONLINE_ORDER";
            String channel = paymentMethod.toString();
            
            result = paymentHandler.payOrder(orderNo, customerId, amount, requestNo, channel);
            
            if(result.isValid()) {
                result.success().message("创建并且手动支付成功");
            } else {
                result.fail().message("创建订单成功但手动支付失败，请手工手动支付");
            }
            
        } catch (Exception e) {
            
            logger.error("onCreate() error: " , e);
            
            result.fail().message("创建订单失败");
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * 
     */
    @RequestMapping(value = "/create-give", method = RequestMethod.GET)
    public ModelAndView createGive() {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/operations/give-order-create");
        
        modelAndView.addObject("products", productService.listGive());
        
        return modelAndView;
        
    }
    
    
    /**
     * 
     */
    @RequestMapping(value = "/create-experience", method = RequestMethod.GET)
    public ModelAndView createExperience() {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/operations/experience-order-create");
        
        modelAndView.addObject("products", productService.listExperience());
        
        return modelAndView;
        
    }
    
    @RequestMapping(value = "/create-year", method = RequestMethod.GET)
    public ModelAndView createYear() {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/operations/year-order-create");
        
        modelAndView.addObject("products", productService.listGive());
        
        return modelAndView;
        
    }
    
    @RequestMapping(value = "/create-card", method = RequestMethod.GET)
    public ModelAndView createCard() {
        
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/operations/card-order-create");
        
        modelAndView.addObject("products", productService.listGive());
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param orderType
     * @param mobile
     * @param productId
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/create-give", method = RequestMethod.POST)
    public @ResponseBody String onCreateGive(@PathVariable("type") String orderType,
                                             @RequestParam("mobile") String mobile,
                                             @RequestParam("name") String name,
                                             @RequestParam("code") String code,
                                             @RequestParam("token") String token,
                                             @RequestParam("productId") Long productId,
                                             @RequestParam(name = "userSourceType", required = false) Long userSourceType,
                                             @RequestParam("siteId") Long siteId) {
        
        Result result = new Result();
        
        try {
        	
        	String vtoken = DigestUtils.sha256Hex(com.demo2do.core.utils.StringUtils.connect(mobile, code, "fitstart"));
            logger.info("#checkVerifyCode   token is [{}] and vtoken is [{}]",token,vtoken);
            boolean validateMObile = StringUtils.equals(vtoken, token);
            
            if(!validateMObile) {
            	result.fail().message("手机验证码不正确");
                return JsonUtils.toJsonString(result);
            }
            
            Product product = productService.load(Product.class, productId);
            Site site = siteService.load(siteId);
            
            if(!"give".equals(orderType)) {
                result.fail().message("只可添加赠课订单");
            } else {
             // Step1 create order by product & 
                Order order = orderService.createGive(mobile.trim(), name, product, site, userSourceType);
                
                String orderNo = order.getCode();
                Long customerId = order.getUser().getId();
                int amount = order.getPrice();
                String requestNo = "ADMIN_CREATED_GIVE_ORDER";
                String channel = PaymentMethod.OTHER.toString();
                
                result = paymentHandler.payOrder(orderNo, customerId, amount, requestNo, channel);
                
                if(result.isValid()) {
                    result.success().message("创建并且手动支付成功");
                } else {
                    result.fail().message("创建订单成功但支付失败，请手动支付");
                }
            }
            
        } catch (Exception e) {
            
            logger.error("onCreateGive() error: " , e);
            
            result.fail().message("创建赠课订单失败");
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    
    @RequestMapping(value = "/create-experience", method = RequestMethod.POST)
    public @ResponseBody String onCreateExperience(@PathVariable("type") String orderType,
                                             	   @RequestParam("mobile") String mobile,
                                             	   @RequestParam("name") String name,
                                             	   @RequestParam(value = "code", required = false) String code,
                                             	   @RequestParam(value = "token", required = false) String token,
                                                   @RequestParam(name = "userSourceType", required = false) Long userSourceType,
                                             	   @RequestParam("productId") Long productId,
                                             	   @RequestParam("siteId") Long siteId) {
        
        Result result = new Result();
        
        try {
        	
        	String vtoken = DigestUtils.sha256Hex(com.demo2do.core.utils.StringUtils.connect(mobile, code, "fitstart"));
            logger.info("#checkVerifyCode   token is [{}] and vtoken is [{}]",token,vtoken);
            boolean validateMObile = StringUtils.equals(vtoken, token);
            
            if(!validateMObile) {
            	result.fail().message("手机验证码不正确");
                return JsonUtils.toJsonString(result);
            }
            
            Product product = productService.load(Product.class, productId);
            Site site = siteService.load(siteId);
            
            if(!"experience".equals(orderType)) {
                result.fail().message("只可添加体验订单");
            } else {
            	
            	// validate user experience count
                orderService.validateUserExperienceCount(product, mobile);
            	
                // Step1 create order by product & 
                Order order = orderService.createExperience(mobile.trim(), name, product, site, userSourceType);
                
                String orderNo = order.getCode();
                Long customerId = order.getUser().getId();
                int amount = order.getPrice();
                String requestNo = "ADMIN_CREATED_GIVE_ORDER";
                String channel = PaymentMethod.OTHER.toString();
                
                result = paymentHandler.payOrder(orderNo, customerId, amount, requestNo, channel);
                
                if(result.isValid()) {
                    result.success().message("创建并且手动支付成功");
                } else {
                    result.fail().message("创建订单成功但支付失败，请手动支付");
                }
            }
            
        } catch (BusinessException e) {
        	
        	logger.error("onCreateGive() error: " , e);
        	result.fail().message(e.getMessage());
        	
        } catch (Exception e) {
            
            logger.error("onCreateGive() error: " , e);
            
            result.fail().message("创建体验课订单失败");
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     *
     * @param mobile
     * @param siteId
     * @param courseHour
     * @return
     * */
    @RequestMapping(value = "/create-year", method = RequestMethod.POST)
    public @ResponseBody String onCreateYear(
                        @RequestParam("mobile") String mobile,
                        @RequestParam("name") String name,
                        @RequestParam("siteId") Long siteId,
                        @RequestParam("code") String code,
                        @RequestParam("token") String token,
                        @RequestParam("productId") CourseUnit courseUnit,
                        @RequestParam(name = "userSourceType", required = false) Long userSourceType,
                        @RequestParam(name = "couponCode", required = false) String couponCode) {
        Result result = new Result();
             try {
            	
            	 String vtoken = DigestUtils.sha256Hex(com.demo2do.core.utils.StringUtils.connect(mobile, code, "fitstart"));
                 logger.info("#checkVerifyCode   token is [{}] and vtoken is [{}]",token,vtoken);
                 boolean validateMObile = StringUtils.equals(vtoken, token);
                 Coupon coupon = null;
                 if(!validateMObile) {
                 	result.fail().message("手机验证码不正确");
                     return JsonUtils.toJsonString(result);
                 }
            	 
                Product product1 = productService.getProduct(courseUnit, CourseType.YEAR);
                Site site = siteService.load(siteId);
                
                if(StringUtils.isNotBlank(couponCode)) {
                    coupon = couponService.loadCoupon(couponCode);
                    if(coupon == null) {
                        result.fail().message("无对应的优惠券");
                        return JsonUtils.toJsonString(result);
                    }
                    
                    if(coupon.getDiscountType().equals(DiscountType.GIFT)) {
                        result.fail().message("礼品券不可用于下单");
                        return JsonUtils.toJsonString(result);
                    }
                    if(!coupon.isAvaliable()) {
                        result.fail().message("优惠券不在使用期限内");
                        return JsonUtils.toJsonString(result);
                    }
                    
                    if(!coupon.getStatus().isUnclaimed()) {
                        result.fail().message("优惠券已使用");
                        return JsonUtils.toJsonString(result);
                    }
                }
                
                orderService.createOrderYear(mobile.trim(), name, product1, site, coupon, userSourceType);
                //String orderNo = order.getCode();
                //Long customerId = order.getUser().getId();
                //int amount = order.getPrice();
                //String requestNo = "ADMIN_CREATED_ORDER_IN";
                //String channel = PaymentMethod.OTHER.toString();
                //result = paymentHandler.payOrder(orderNo, customerId, amount, requestNo, channel);
                //if (result.isValid()) {
                //    result.success().message("创建并且手动支付成功");
                //} else {
                //    result.fail().message("创建订单成功但支付失败，请手动支付");
                //}
                result.success().message("创建课程订单成功，未支付");

            } catch (Exception e) {
                logger.error("onCreateYear error", e);
                result.fail().message("创建课程订单失败");
            }


        return JsonUtils.toJsonString(result);

    }
    
    /**
    *
    * @param mobile
    * @param siteId
    * @param courseHour
    * @return
    * */
   @RequestMapping(value = "/create-card", method = RequestMethod.POST)
   public @ResponseBody String onCreateCard(
                       @RequestParam("mobile") String mobile,
                       @RequestParam("name") String name,
                       @RequestParam("siteId") Long siteId,
                       @RequestParam("code") String code,
                       @RequestParam("token") String token,
                       @RequestParam("productId") CourseUnit courseUnit,
                       @RequestParam(name = "userSourceType", required = false) Long userSourceType,
                       @RequestParam(name = "couponCode", required = false) String couponCode) {
       Result result = new Result();
            try {
           	
           	 String vtoken = DigestUtils.sha256Hex(com.demo2do.core.utils.StringUtils.connect(mobile, code, "fitstart"));
                logger.info("#checkVerifyCode   token is [{}] and vtoken is [{}]",token,vtoken);
                boolean validateMObile = StringUtils.equals(vtoken, token);
                Coupon coupon = null;
                if(!validateMObile) {
                	result.fail().message("手机验证码不正确");
                    return JsonUtils.toJsonString(result);
                }
           	 
               Product product1 = productService.getProduct(courseUnit, CourseType.CARD);
               Site site = siteService.load(siteId);
               
               if(StringUtils.isNotBlank(couponCode)) {
                   coupon = couponService.loadCoupon(couponCode);
                   if(coupon == null) {
                       result.fail().message("无对应的优惠券");
                       return JsonUtils.toJsonString(result);
                   }
                   
                   if(coupon.getDiscountType().equals(DiscountType.GIFT)) {
                       result.fail().message("礼品券不可用于下单");
                       return JsonUtils.toJsonString(result);
                   }
                   if(!coupon.isAvaliable()) {
                       result.fail().message("优惠券不在使用期限内");
                       return JsonUtils.toJsonString(result);
                   }
                   
                   if(!coupon.getStatus().isUnclaimed()) {
                       result.fail().message("优惠券已使用");
                       return JsonUtils.toJsonString(result);
                   }
               }
               
               orderService.createOrderCard(mobile.trim(), name, product1, site, coupon, userSourceType);
               result.success().message("创建课程订单成功，未支付");

           } catch (Exception e) {
               logger.error("onCreateYear error", e);
               result.fail().message("创建课程订单失败");
           }


       return JsonUtils.toJsonString(result);

   }

}
